<template>
  <a class="get-validate" :class="{gray: (!stop)}" @click="clickHandler">{{ text }}</a>
</template>

<script>
export default {
  name: 'Clock',
  props: {
    timer: {
      default: 60,
      type: Number
    }
  },
  data() {
    return {
      stop: true,
      mytimer: this.timer,
      Interval: null,
      text: '获取验证码'
    }
  },
  methods: {
    clickHandler(e) {
      if (this.stop) {
        // 调用外部绑定的倒计时，并且给它开关
        this.$emit('click', this.startTimer)
      }
    },
    update() {
      if (this.mytimer <= 1) {
        // 重置计数
        this.mytimer = this.timer
        // 清除计时器
        clearInterval(this.Interval)
        // 允许启动倒计时
        this.stop = true
        this.text = '重新获取'
      } else {
        // 倒计时
        this.mytimer--
        this.text = `(${this.mytimer})秒后重新获取`
      }
    },
    startTimer() {
      // 开始循环执行update函数
      this.text = `(${this.mytimer})秒后重新获取`
      this.Interval = setInterval(this.update, 1000)
      // 禁止启动倒计时
      this.stop = false
    }
  }
}

</script>

<style lang="scss" scoped>
  .get-validate {
    display: inline-block;
    padding: 0 10px;
    text-align: right;
    color: #449cff;
    cursor: pointer;

    &.gray {
      color: #ddd;
      cursor: not-allowed;
    }
  }
</style>
